<template>
	<div class="mainCon">
		<div class="mainCon">
			<div class="containercontent">
				<div class="penalrow selectw100">
					<div class="inlineblock verticalmiddle infoitem">
						<div class="inlineblock verticalmiddle">
							类型
						</div>
						<div class="inlineblock verticalmiddle informationItem" >
							<el-cascader clearable @change="cascaderChange" expand-trigger="hover" :options="enableMaterTypeList" v-model="selectedOptions2"
							 size="mini" style="width:100%;">
							</el-cascader>
						</div>
					</div>
					<div class="inlineblock verticalmiddle infoitem">
						<div class="inlineblock verticalmiddle">
							名称
						</div>
						<div class="inlineblock verticalmiddle informationItem">
							<el-input style="" v-model="stockListParams.materialName" size="mini" placeholder="物资名称" clearable @keyup.enter.native="doSearch"></el-input>
						</div>
					</div>
					<div class="inlineblock verticalmiddle infoitem">
						<div class="inlineblock verticalmiddle">
							是否报警
						</div>
						<div class="inlineblock verticalmiddle informationItem">
							<el-select v-model="stockListParams.warn"  placeholder="请选择" size="mini" @change = "doSearch" >
								<el-option v-for="item in yesorno" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</div>
					</div>
          <div class="inlineblock verticalmiddle infoitem">
          	<div class="inlineblock verticalmiddle">
          		是否过期
          	</div>
          	<div class="inlineblock verticalmiddle informationItem">
          		<el-select v-model="stockListParams.dateStatus"  placeholder="请选择" size="mini" @change = "doSearch" >
          			<el-option v-for="item in yesorno" :key="item.value" :label="item.label" :value="item.value">
          			</el-option>
          		</el-select>
          	</div>
          </div>
					<div style="">
						<el-button type="warning" size="mini" @click="doSearch">搜索 </el-button>
						<el-button type="warning" size="mini" @click="emptySearch">清空 </el-button>
					</div>
				</div>
				<div class="separaterowTable">
					<div class="tableTittle">
						<div><span class="fontImpact">1</span><span>库存列表</span></div>
               		    <el-button type="primary" size="mini" style="float: right;" @click="exportStockdet" v-if="userOpernation.export.display">导出</el-button>
					</div>
					 <!---->
					<el-table :data="tableData6" :cell-class-name="cellclassnamefunction" size='mini' @expand-change="expandChange" @row-click="rowClick" style="width: 100%;height:calc(100% - 80px)"
					 class="tableCon" :expand-row-keys="expands"  row-key="materialCode">
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-table :data="subTable" v-if="showTable" v-loading="loading" size='mini' style="width:100%;margin:auto;">
									<el-table-column label="序号" min-width="50px">
										<template slot-scope="scope">
											{{scope.$index+(readQuery.page - 1) * readQuery.pageCount + 1}}
										</template>
									</el-table-column>
									<el-table-column prop="number" min-width="120px" label="物资编号" show-overflow-tooltip>
									</el-table-column>
									<el-table-column prop="materialName" label="名称" min-width="120px" show-overflow-tooltip>
									</el-table-column>
									<el-table-column prop="batch" min-width="120px" label="批号">
									</el-table-column>
									<el-table-column prop="concentration" label="浓度" :formatter="formatter">
									</el-table-column>
									<el-table-column prop="purity" label="纯度" :formatter="formatter">
									</el-table-column>
									<el-table-column prop="medium" label="介质" :formatter="formatter">
            						</el-table-column>
									<el-table-column width="100px" prop="qty" label="余量">
										<!--<template slot-scope="scope">
											<span v-if="!scope.row.qctedit">{{scope.row.qty}}</span>

											<el-input v-if="scope.row.qctedit"  class="deal" oninput="this.value=this.value.replace(/[^0-9.]+/,'');" v-model="scope.row.qty" :min="1"  label="描述文字" size="mini"></el-input>
										</template>-->
									</el-table-column>
									<el-table-column prop="validitydate" label="有效期"  min-width="110px">
										<template slot-scope="scope">
											{{scope.row.hasOwnProperty('validitydate')?scope.row.validitydate.split('.')[0]:'/'}}

										</template>
									</el-table-column>
									<el-table-column width="120px" label="操作">
										<template slot-scope="scope">
											<!-- <el-button @click="qtyEdit(scope.row)" size="mini" type="text" v-if="userOpernation.update.display">设置</el-button> -->
											<!-- <el-button @click="sampleSet(scope.row,'look')" size="mini" type="text" v-if="userOpernation.select.display" :disabled="scope.row.itemStandardList.length==0">标样详情</el-button> -->
                      <el-button @click="yuliangEdit(scope.row,'edit')" size="mini" type="text" v-if="userOpernation.openUpdate.display">编辑</el-button>
                      <el-button @click="yuliangEdit(scope.row,'look')" size="mini" type="text" v-if="userOpernation.select.display">详情</el-button>
                    </template>
									</el-table-column>
								</el-table>
							</template>
						</el-table-column>
						<el-table-column label="序号" width="50px">
							<template slot-scope="scope">
								{{scope.$index+1}}
							</template>
						</el-table-column>
						<el-table-column prop="materialName" label="名称" min-width="80px" show-overflow-tooltip>

						</el-table-column>
						<el-table-column prop="materialTypeName" label="类型" min-width="80px" show-overflow-tooltip>
						</el-table-column>
						<el-table-column label="预警值" min-width="80px" prop = "safetyQty" :formatter="formatter">

						</el-table-column>
						<el-table-column prop="qty" label="总量" min-width="60px">

						</el-table-column>
						<el-table-column prop="shichushuliang" label="预警状态" min-width="60px">
							<template slot-scope="scope">
								<el-button v-if="scope.row.qty < scope.row.safetyQty " size="mini" type="text">
									<img src="../../../assets/img/clock.svg" width="20px" />
								</el-button>
                <span v-if="scope.row.safetyQty == undefined || scope.row.safetyQty == null || scope.row.safetyQty == '' ||scope.row.qty >= scope.row.safetyQty ">---</span>

							</template>
						</el-table-column>
						<el-table-column prop="shichushuliang" label="操作" min-width="60px" v-if="userOpernation.update.display">
							<template slot-scope="scope">
								<el-button @click.stop="addSafetyQty(scope.row)" size="mini" type="text">设置</el-button>
							</template>
						</el-table-column>

					</el-table>
					<div class="block changepages">
						<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="readQuery.page" :page-sizes="[20, 30, 40]"
						 :page-size="readQuery.pageCount" layout="total, sizes, prev, pager, next, jumper" :total="rowNumber">
						</el-pagination>
					</div>
				</div>
			</div>

    </div>

		<el-dialog :visible.sync="editShow" width="55%" :show-close='false' :closeOnClickModal='false'>
			<span slot="title" class="dialog-title">
		  		设置预警值
			    <el-button @click="resetForm" size="mini" class="popupClose">关闭</el-button>
			  </span>
			<el-form label-width="110px" :inline="false" class="demo-form-inline" :model="sisForm"  ref="sisForm" >
				<el-form-item label="预警值" prop="safetyQty">
					<el-col :span="22">
						<el-input placeholder="预警值" size="mini" v-model="sisForm.safetyQty" class="deal" oninput="this.value=this.value.replace(/[^0-9]+/,'');" ></el-input>
					</el-col>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
			    <el-button type="primary" @click="submitForm()" size="mini" >确 定</el-button>
			    <el-button  size="mini" @click="resetForm()">取 消</el-button>
			  </span>
		</el-dialog>
		<el-dialog :visible.sync="editQtyShow" width="55%" :show-close='false' :closeOnClickModal='false'>
			<span slot="title" class="dialog-title">
		  		设置余量
			    <el-button @click="resetQtyForm" size="mini" class="popupClose">关闭</el-button>
			  </span>
			<el-form label-width="110px" :inline="false" class="demo-form-inline" :model="editQtyForm"  ref="editQtyForm" :rules = "editQtyFormRules">
				<el-form-item label="余量" prop="qty">
					<el-col :span="22">
						<el-input placeholder="余量" size="mini"  v-model="editQtyForm.qty" class="deal" oninput="this.value=this.value.replace(/[^0-9]+/,'');" ></el-input>
					</el-col>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
			    <el-button type="primary" @click="updateStockQty()" size="mini"  :disabled = "!isRepeat">确 定</el-button>
			    <el-button  size="mini" @click="resetQtyForm()">取 消</el-button>
			  </span>
		</el-dialog>
    <div v-if="qualitySampleAddShow">
    	<quality-sample-add :bjorck="bjorck" :selectRow.sync="selectRow" :samplesetObj.sync="samplesetObj" :noshenhe="true"></quality-sample-add>
    </div>
    <div v-if = "editYuliangShow">
        <yuliangEdit  :isEdit = "isEdit" :yuliangForm = "yuliangForm"></yuliangEdit>
    </div>
  </div>
</template>

<script>
	import { mapState } from 'vuex'
	const qualitySampleAdd = () => import('../../qualityControl/qualityControl/children/qualitySampleAdd.vue');
  const yuliangEdit = () => import('./yuliangEdit.vue');
	export default {
		data() {
			return {
				loading: false,
				showTable: true,
				enableStatusValue: '',
				searchName: '',
				currentPage: 1,
				materialTypeValue: '',
				options: [],
				selectedOptions2: [],
				tableData7: [],
				tableData6: [],
				pageinfo: {},
				stockListParams: {
					materialType: '',
					materialName: '',
					warn:false,
          dateStatus:false
				},
				readQuery: {
					page: 1,
					pageCount: 20
				},
				rowNumber: 0,
				firstleixingindex: 0,
				leixingnum: 0,
				firstwupinindex: 0,
				wupinnum: 0,
				firstbaozhuangindex: 0,
				baozhuangnum: 0,
				qualitySampleAddShow: false,
				bjorck: '',
				num1: 10,
				samplesetObj:{},
				editShow:false,
				sisForm:{
					safetyQty:null,
					code:null
				},
				isRepeat:true,
				editQtyShow:false,
				editQtyForm:{
					id:null,
					qty:null,
				},
				expands: [],// 要展开的行，数值的元素是row的key值
				oldRow:null,
				subTable:[],
				editQtyFormRules:{
					qty:[{required: true, message: '请填写余量', trigger: 'blur' }]
				},
        editYuliangShow:false,
        isEdit:"edit",
        yuliangForm:{},
			}
		},
		computed: {
			tabDivHeight() {
				return (window.innerHeight - 280)
			},
			...mapState(['enableStatus', 'tableHeightA', 'typeofAbilityTableDate', 'materialType', 'enableMaterTypeList','yesorno']),
		},
		props: ['userOpernation','nowTab'],
		components: {
			qualitySampleAdd,
      yuliangEdit
		},
		mounted() {

			this.readStockList()
			this.readEnableMaterTypeList()
			console.log(this.nowTab)
		},
		watch: {
			readQuery: {
				handler(val, oldVal) {
					this.readStockList()
				},
				deep: true
			},
			'nowTab'(val){
				console.log(val)
				if(val == 'yuliang'){

					var pagePath = JSON.parse(sessionStorage.getItem('pageObj'));
					if(pagePath != undefined && pagePath.oldPage == "homePage"){
						this.stockListParams.warn = true;
					}else{
						this.stockListParams.warn = false;
					}
				}else{
					sessionStorage.removeItem('pageObj')
				}
			}
		},
		methods: {
			exportStockdet() {
				var url = "/resource/exportStock.htm"
				let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?materialType=' + this.stockListParams.materialType + '&materialName=' + this.stockListParams.materialName + '&warn=' + this.stockListParams.warn + '&dateStatus=' + this.stockListParams.dateStatus + "&token=" + token);
			},
      formatter(row, column, cellValue, index) {
        if(cellValue == undefined || cellValue == null || cellValue == ""){
          return "---"
        }else{
          return cellValue
        }
      },
			//	余量编辑和保存
			qtyEdit(row) {
				this.editQtyShow = true;
				this.editQtyForm = JSON.parse(JSON.stringify(row));
				this.editQtyForm.id = row.id;
				this.editQtyForm.qty = row.qty;

			},
      yuliangEdit(row,isEdit){
        this.isEdit = isEdit;
        this.yuliangForm = JSON.parse(JSON.stringify(row));
        this.editYuliangShow = true;
      },

			//	updateStockQty.htm
			//参数   库存id:   id      库存数量：qty      非json
			updateStockQty() {
				this.$refs.editQtyForm.validate((valid) => {  //表单验证
					if (valid) {
						let params = { id: this.editQtyForm.id, qty: this.editQtyForm.qty }
						this.$http({
							apiUrl: 'resource/updateStockQty.htm',
							method: 'post',
							params: params,
							isJson: false
						}).then(res => {
							if (res.code === 0) {
								this.$message({
									showClose: true,
									message: '保存成功！',
									type: 'success'
								})
								this.expandChange(this.editQtyForm,this.editQtyForm,'change')
								this.readStockList();

								this.resetQtyForm();
							}
						})
					}
				})

			},
			resetQtyForm(){
				this.editQtyShow = false;
			},
			//	17、(1)交互名称：获取物资级联列表
			readEnableMaterTypeList() {
				function isClass(o) {
					if (o === null) return "Null";
					if (o === undefined) return "Undefined";
					return Object.prototype.toString.call(o).slice(8, -1);
				}
				function deepClone(obj) {
					var result, oClass = isClass(obj);
					//确定result的类型
					if (oClass === "Object") {
						result = {};
					} else if (oClass === "Array") {
						result = [];
					} else {
						return obj;
					}
					for (let key in obj) {
						var copy = obj[key];
						if (isClass(copy) === "Object") {
							result[key] = deepClone(copy);//递归调用
						} else if (isClass(copy) === "Array") {
							if (key == 'materialTypeBeanList' && obj[key].length != 0) {
								result['children'] = deepClone(copy)
							}
						} else {
							if (key == 'code') {
								result['value'] = obj[key]
							}
							if (key == 'name') {
								result['label'] = obj[key]
							}
							//        	result[key] = obj[key]
						}
					}
					return result;
				};

				this.$http({
					apiUrl: 'technology/readEnableMaterTypeList.htm',
					method: 'post',
					params: null,
				}).then(res => {
					if (res.code === 0) {
						this.options = deepClone(res.data)
					}
				})
			},
			cascaderChange() {
				this.stockListParams.materialType = this.selectedOptions2[this.selectedOptions2.length - 1]
				this.doSearch();
				//			this.readStockList()
			},
			//	15、(1)交互名称：获取库存余量列表
			// (2)url:readStockList.htm
			// (3)参数：
			readStockList() {
				this.stockListParams.page = this.readQuery.page;
				this.stockListParams.pageCount = this.readQuery.pageCount;

				this.$http({
					apiUrl: 'resource/readStockList.htm',
					method: 'post',
					params: this.stockListParams
				}).then(res => {
					if (res.code === 0) {
						this.tableData6 = res.data
						this.tableData6.forEach((item, index) => {
							item.check = false;
							// item.subTable = []
						})
						this.pageinfo = res.pageinfo
						if (!res.pageinfo) {
							this.rowNumber = 0;
						} else if (res.pageinfo && !res.pageinfo.rowNumber) {
							this.rowNumber = 0;
						} else {
							this.rowNumber = res.pageinfo.rowNumber;
						}
					}
				})
			},
			//	16、(1)交互名称：根据materialCode获取相同物资、不同hashcode的库存余量
			// (2)url:readStockByMatarialCode.htm
			// (3)参数：materialCode
			readStockByMatarialCode(materialCode) {

				return new Promise((resolve, reject) => {
					this.$http({
						apiUrl: 'resource/readStockByMatarialCode.htm',
						method: 'post',
						params: { materialCode: materialCode }
					}).then(res => {
						if (res.code === 0) {
							console.log(res)

							resolve(res)
						}
					})
				})

			},
			addSafetyQty(row) {

				this.sisForm.safetyQty = row.safetyQty;
				this.sisForm.code = row.materialCode;
				this.editShow = true;
			},
			submitForm(){
				this.$http({
					apiUrl: 'resource/addSafetyQty.htm',
					method: 'post',
					params: this.sisForm,
					isJson: true
				}).then(res => {
					if (res.code === 0) {
						console.log(res)
						this.$message({
							showClose: true,
							message: '保存成功！',
							type: 'success'
						})
						this.resetForm();

						this.readStockList()
					}
				})
			},
			resetForm(){
				this.editShow = false;
			},

			expandChange(row, expandedRows,operate) {
				if (operate == undefined) {  //点击小三角时operate == undefined  ，operate随意传一个值，不为undefed即可 只刷新展开的
					if (this.expands.indexOf(row.materialCode) < 0) {
					this.expands = [];
					this.expands.push(row.materialCode);
					} else {
					this.expands.pop(row.materialCode);
					}
				}
				if (expandedRows.length > 1) {
					expandedRows.shift()
				}
				if (this.oldRow && this.oldRow != row) {
					this.oldRow.check = false;
				}
				row.check = !row.check;
				this.oldRow = row;
				if (row.check) {
					// this.loading = true;
					this.readStockByMatarialCode(row.materialCode).then(res => {
						// row.subTable = res.data
						this.subTable = res.data;
						// this.$nextTick(() => {
						// 	this.loading = false;
						// })
					})
				}

			},
			rowClick(row, column, event) {
				Array.prototype.remove = function (val) {
					let index = this.indexOf(val);
					if (index > -1) {
						this.splice(index, 1);
					}
				};
				if (this.expands.indexOf(row.materialCode) < 0) {
					this.expands = [];
					this.expands.push(row.materialCode);
					this.loading = true;
					this.readStockByMatarialCode(row.materialCode).then(res => {
						// row.subTable = res.data
						this.subTable = res.data;
						this.$nextTick(() => {
							this.loading = false;
						})
					})

				} else {
					this.expands.remove(row.materialCode);
				}
				delete Array.prototype['remove'];

			},
			emptySearch() {
				this.stockListParams.materialName = "";
				this.selectedOptions2 = [];
				this.stockListParams.materialType = ""
				this.stockListParams.warn = false;
        this.stockListParams.dateStatus = false;
				this.doSearch();
			},
			doSearch() {
				this.readQuery.page = 1;
				this.readStockList()
			},
			handleSizeChange(val) {
				this.readQuery.pageCount = val;
			},
			handleCurrentChange(val) {
				this.readQuery.page = val;
			},
			sampleSet(row, flag) {
				this.selectRow = row
				if (!this.selectRow.hasOwnProperty('itemStandardList')) {
					this.selectRow.itemStandardList = []

				}
				this.qualitySampleAddShow = true;
				this.bjorck = flag

			},
			//			3、(1)交互名称：获取标样设置列表
			// 			(2)url:readSampleSet.htm
			readSampleSet(hashcode) {
				return new Promise((resolve, reject) => {
					this.$http({
						apiUrl: 'resource/readSampleSet.htm',
						method: 'post',
						params: { hashcode: hashcode },
						isJson: false
					}).then(res => {
						if (res.code === 0) {
							console.log(res)
							resolve(res)
						}
					}).catch(err => {
						console.log(err)
					})
				})
			},
			changeUserStatus: function (row) {
				console.log(row);
			},

			objectSpanMethod({ row, column, rowIndex, columnIndex }) {
				if (columnIndex === 0) {
					return {
						rowspan: row.leixingrownum,
						colspan: 1
					}
				} else if (columnIndex === 1) {
					return {
						rowspan: row.wupinnum,
						colspan: 1
					}
				}
			},
			cellclassnamefunction({ row, column, rowIndex, columnIndex }) {
				if (row.baozhuangguige == '小计' && columnIndex > 1) {
					return 'xiaoJiTableCell'
				}
				return ''
			}
		}
	}

</script>

<style scoped>
	.infoitem{
		width:calc(100%/5)
	}
  .informationItem{
    width: calc(100% - 64px);
  }
	.red {
		color: red;
	}

	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {
		width: 90px;
		color: #99a9bf;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}
</style>
